<?php
/* 
 * Copyright (c) 2018-2021   All rights reserved.
 * 
 * 创建时间：2021-08-27 09:36
 *
 * 项目：rm  -  $  - Native.php
 *
 * 作者：liwei 
 */

namespace modules\levpays\sdk\wechatpay\native;

use Lev;
use modules\levpays\helpers\levpaysSetHelper;
use modules\levpays\sdk\wechatpay\InstancePay;
use modules\levpays\table\tradesHelper;

!defined('INLEV') && exit('Access Denied LEV');

class Native extends InstancePay
{

    public static function tradePre() {
        return 'NATIVE-'.levpaysSetHelper::tradePre();
    }

    /**
     * @param $tradeNo
     * @param $desc
     * @param $money
     * @return string
     */
    public static function PlaceOrder($tradeNo, $desc, $money) {
        $money *= 100;//110 会提示不合法，不明所以

        $instance = static::init();
        if (!$instance) return '';
        $pre = static::tradePre();
        try {
            $resp = $instance->v3->pay->transactions->native
                ->post(['json' => [
                    'mchid'        => static::$config['mchid'],
                    'out_trade_no' => InstancePay::getOutTradeNo($tradeNo, $pre),
                    'appid'        => static::$config['appid'],
                    'description'  => $desc, //'Image形象店-深圳腾大-QQ公仔',
                    //'notify_url'   => Lev::toReRoute(['default/notify-native']),
                    'notify_url'   => InstancePay::notifyUrl(),
                    'amount'       => [
                        'total'    => $money,//单位：分
                        'currency' => 'CNY'
                    ],
                ]]);
        } catch (\Exception $e) {
            // 进行错误处理
            //echo $e->getMessage(), PHP_EOL;
            if ($e instanceof \GuzzleHttp\Exception\RequestException && $e->hasResponse()) {
                $resp = $e->getResponse();
            }
            //echo $e->getTraceAsString(), PHP_EOL;
        }
        $res = json_decode($resp->getBody(), true);//print_r($res);
        if (empty($res['code_url'])) {
            Lev::setNotices($res['code'].'：'.$res['message']. $money);
            InstancePay::paySuccess($res, $tradeNo, $pre);
            return '';
        }
        tradesHelper::setTradePaysource($tradeNo, $pre);
        return $res['code_url'];
    }

    public static function notify() {
        file_put_contents(__DIR__ . '/notify.txt', print_r($_POST, true).'----'.file_get_contents("php://input"), FILE_APPEND);
        return json_encode(['code'=>'SUCCESS', 'message'=>'成功'], JSON_UNESCAPED_UNICODE);
    }

    public static function checkTradeNo($tradeNo)
    {
        $tradeNo = parent::getOutTradeNo($tradeNo, static::tradePre());
        return parent::checkTradeNo($tradeNo); // TODO: Change the autogenerated stub
    }
}